<?php
namespace app\admin\controller;

use app\common\controller\Base;
use think\facade\View;

class Member extends Base
{
    protected $config=[
        'modelName'=>'Member',
    ];
    public function __construct()
    {
        parent::__construct();
        $this->model=model($this->config['modelName']);

    }

    public function index()
    {
        $data=$this->model::all();
        View::share('data',$data);
        return view();
    }

    /**
     * 添加方法
     * @param \think\Request $request
     * @return \think\response\View
     */
    public function addC(\think\Request $request){
        if($request->isPost()){
            $data=$request->post();
            $data['password']=password_hash($data['password'],PASSWORD_DEFAULT);
            // $data=$this->filedCover($data,['username'=>'mname']);
            $check=$this->validation('\app\admin\validate\Member',$data);
            if($check['status']===0){
                $this->error($check['msg']);
            }
            $res=$this->model->save($data);
            $res?$this->success('执行成功','index'):$this->error('执行失败'.$this->model->getError(),'index');
        }
        View::share(['title'=>'用户添加']);
        return view('store');
    }

    /**
     * 编辑方法
     */
    public function editC($id){
        if($this->request->isPost()){
            $data=$this->request->post();
            //处理开关选项
            $data['is_super']=isset($data['is_super'])?$data['is_super']:'0';
            $data['status']=isset($data['status'])?$data['status']:'0';
            $check=$this->validation('app\admin\validate\Member',$data);
            if($check['status']==0) $this->error($check['msg']);
            $id=intval($id);
            $res=$this->model->save($data,['id'=>$id]);
            $res?$this->success('执行成功','index'):$this->error("执行失败".$this->model->getError(),'index');
        }
        $oldData=$this->model->field('id,mname,is_super,image,status')->find($id);
        View::share(['title'=>'用户编辑','oldData'=>$oldData]);
        return view('store');
    }

    public function delC(){
        $data=$this->request->post();
        $check=$this->validation('think\Validate',$data,'',['id'=>'require|token']);
        if($check['status']==0) return false;
        // 删除用户时需要删除相关的中间表

        $this->model->id=$data['id'];
        $this->model->groupRel()->detach();
        $res=$this->model::destroy($data['id']);
        $back=$res?'删除成功':'删除失败'.$this->model->getError();
        return $back;
    }

}
